import {constructOne, FormWidget, queryOne, SPI, ViewWidget,  Widget, IModel, getModelByUrl,  getModel,  getIdByUrl, CustomWidget, CallChaining } from "@kunlun/dependencies";

import PetFormView from './PetForm.vue'

@SPI.ClassFactory(CustomWidget.Token({ widget: 'PetForm' }))
export class PetFormViewWidget extends FormWidget {

  public initialize(props) {
    super.initialize(props);
    this.setComponent(PetFormView);
    return this;
  }

  @Widget.Reactive()
  @Widget.Inject()
  protected callChaining: CallChaining | undefined;

  private modelInstance!: IModel;

  @Widget.Method()
  public onFieldChange(fieldName: string, value) {
    // this.setDataByKey(fieldName, value);
  }

  // public async fetchData(content: Record<string, unknown>[] = [], options: Record<string, unknown> = {}, variables: Record<string, unknown> = {}) {

  //   this.setBusy(true);
  //   const context: typeof options = { sourceModel: this.modelInstance.model, ...options};
  //   const fields = this.modelInstance?.modelFields;
  //   try {

  //     const id = getIdByUrl();
  //     const data = (await queryOne(this.modelInstance.model, (content[0] || {id}) as Record<string, string>, fields , variables, context)) as Record<string, unknown>;

  //     this.loadData(data);
  //     this.setBusy(false);

  //     return data;

  //   } catch (e) {
  //     console.error(e)
  //   } finally {
  //     this.setBusy(false)
  //   }
  // }

  // @Widget.Method()
  // public async constructData(content: Record<string, unknown>[] = [], options: Record<string, unknown> = {}, variables: Record<string, unknown> = {}) {

  //   // this.setBusy(true);
  //   const context: typeof options = {sourceModel: this.modelInstance.model, ...options};
  //   const fields = this.modelInstance.modelFields;
  //   const reqData = content[0] || {};
  //   const data = await constructOne( this.modelInstance!.model, reqData, fields, variables, context);
  //   return data as Record<string, unknown>;

  // }

  @Widget.Method()
  public onChange(name, value) {
    this.formData[name] = value;
  }

  protected async mounted() {
    super.mounted();
    const modelModel = getModelByUrl();
    this.modelInstance = await getModel(modelModel);
    this.fetchData();
    this.callChaining?.callBefore(() => {
      return this.formData;
    })
  }


}
